<template>
    <div>
        <Navbar title="登录/注册" icon="cross"></Navbar>
        <van-form >
            <van-field
            v-model="user.mobile"
            left-icon="manager"
            name="手机号"
            placeholder="手机号"
            :rules="[{ required: true, message: '请填写手机号' }]"
          />
            <van-field
        v-model="user.code"
        left-icon="lock"
        name="验证码"
        placeholder="验证码"
        :rules="[{ required: true, message: '输入验证码' }]"
      >
        <template #button>
          <van-button size="small" disabled v-if="isSend == true">
            <van-count-down
              :time="1000 * 10"
              format="sss"
              @finish="isSend = false"
            ></van-count-down>
          </van-button>
          <van-button size="small" type="primary" v-else @click="sendCode"
            >发送验证码</van-button
          >
        </template>
      </van-field>
          </van-form>
    </div>
</template>
<script>

import Navbar from '../../components/navbar'
export default {
  components: { Navbar },
  data(){
      return {
          username:'',
          password:'',
          user:{
              mobile:'',
              code:'',
          },
          isSend:false,
      }
  },
  methods:{
      login(){
      var phone_pertten = /^1[34578]\d{9}$/;
      var code_pertten = /^\d{6}$/;
      if (this.user.monbile == "" || this.user.code == "") {
            this.$toast.fail('手机号或者验证码不能为空')
            return false;
      }
      if(!phone_pertten.test(this.user.mobile)){
          this.$toast.fail('手机格式不正确');
          return flase;
      }
      if (!code_pretten.test(this.user.code)) {
            this.$toast.fail('验证码格式不正确');
            return false;
      }
      this.$axios.post('/authorizations',this.user).then(res=>{
          console.log(res);
          this.$store.commit('login',res.data)
          this.$toast.success('登陆成功');
          let url = this.$route.query.redirect || 'my';
          this.$router.replace(url);
      }).catch((error) =>{
        console.log(error.response.data.message);
        this.$toast.fail('请求登录接口的信息失败');

      })
      },
      sendCode(){
          var phone_pertten = /^1[34578]\d{9}$/
          if(this.user.mobile == ""){
                this.$toast.fail('手机号或者验证码不能为空');

                return false;
          }
          if(!phone_pertten.test(this.user.mobile)){
          this.$toast.fail('手机格式不正确');
          return flase;
      }
          this.isSend = true;
          this.$axios.get('/sms/codes' + this.user.mobile).then(res=>{
              console.log(res);
              this.$toast.success('发送验证码成功')

          }).catch((error) =>{
              console.log(error.response.data.message);
              this.$toast.fail('请求登录接口的信息失败');
          })
      }
  }
    
}
</script>
<style lang="">
    
</style>